import { updateQuestion } from "@/api/question"
import { ProColumns, ProTable } from "@ant-design/pro-components"
import { message, Modal } from "antd"
import React from "react"

interface Props {
  oldData?: Question
  visible: boolean
  columns: ProColumns<Question>[]
  onSubmit: (values: QuestionAddRequest) => void
  onCancel: () => void
}

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: QuestionUpdateRequest) => {
  const hide = message.loading("正在更新")
  try {
    await updateQuestion(fields)
    hide()
    message.success("更新成功")
    return true
  } catch (error) {
    hide()
    error instanceof Error && message.error("更新失败，" + error.message)
    return false
  }
}

/**
 * 更新弹窗
 * @param props
 * @constructor
 */
const UpdateModal: React.FC<Props> = (props) => {
  const { oldData, visible, columns, onSubmit, onCancel } = props

  if (!oldData) {
    return <></>
  }

  const initialValues = { ...oldData }
  if (oldData.tags) {
    initialValues.tags = JSON.parse(oldData.tags || "[]")
  }

  return (
    <Modal
      destroyOnClose
      title={"更新"}
      open={visible}
      footer={null}
      onCancel={() => {
        onCancel?.()
      }}
    >
      <ProTable
        type="form"
        columns={columns}
        form={{
          initialValues: initialValues
        }}
        onSubmit={async (values: QuestionAddRequest) => {
          const success = await handleUpdate({
            ...values,
            id: oldData.id
          })
          if (success) {
            onSubmit?.(values)
          }
        }}
      />
    </Modal>
  )
}
export default UpdateModal
